package com.fnfn.sdk.api.controller;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.fnfn.sdk.api.AjaxResponseData;
import com.fnfn.sdk.api.common.logutil.SysLog;
import com.fnfn.sdk.api.common.msg.MessageProperties;
import com.fnfn.sdk.api.entity.Permission;
import com.fnfn.sdk.api.entity.Wuser;
import com.fnfn.sdk.api.service.UserService;
import com.fnfn.sdk.api.session.TokenUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fnfn.sdk.api.common.AjaxResponse;
import com.fnfn.sdk.api.common.BaseController;
import com.fnfn.sdk.api.common.BeanId;
import com.fnfn.sdk.api.common.MD5;
import com.fnfn.sdk.api.common.ResultCode;
import com.fnfn.sdk.api.entity.User;
import com.fnfn.sdk.api.session.TokenSession;
import com.fnfn.sdk.api.session.TokenSessionManager;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping(value = "token")
@Api(tags = {"token"})
public class TokenController extends BaseController {
    private static final Logger LOGGER = LoggerFactory.getLogger(LoggerFactory.class);

    @Autowired
    private UserService userService;

    @ApiOperation(value = "获取token", notes = "请求参数:<br>" + "username 用户名<br>" + "password 密码")
    @ResponseBody
    @SysLog(value = "获取token", opType = "GetAPIToken")
    @RequestMapping(value = "/GetAPIToken", method = RequestMethod.POST)
    public AjaxResponse GetAPIToken(@RequestBody Wuser user, HttpSession httpSession) {
        LOGGER.info("username={},password={}",user.getUsername(),user.getPassword());
        try {
            User accountInfo = userService.selectDetailByUsername(user.getUsername());
            if (accountInfo == null) {
                LOGGER.warn("accountInfo is null,{},{}", user.getUsername(), user.getPassword());
                return AjaxResponseData.reponseBody(ResultCode.USER_NAME_NOT_EXISTS,"用户不存在", null);
            }
//            if (accountInfo.getStatus() == 3) {
//                return AjaxResponse.reponseBody(ResultCode.USER_IS_DISABLE,
//                        MessageProperties.getValue(ResultCode.USER_IS_DISABLE), null);
//            }

            if (!MD5.getStandardMd5(user.getPassword()).equals(accountInfo.getcPassword())) {
                return AjaxResponseData.reponseBody(ResultCode.USER_NAME_OR_PW_ERROR,"密码不正确", null);
            }
            UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(),
                    MD5.getStandardMd5(user.getPassword()));
            Subject subject = SecurityUtils.getSubject();
            subject.login(token);

            TokenSession session = new TokenSession();

            session.setAccountId(accountInfo.getcUserId());
            session.setAccountName(accountInfo.getcUsername());
            session.setNickName(accountInfo.getcNickname());
            session.setCreateTime(System.currentTimeMillis());
            session.setLatestActiveTime(System.currentTimeMillis());

            JSONArray functionPermissions = new JSONArray();
            Set<String> functionPermissionTokens = new HashSet<>();
            System.out.println("accountInfo.getcPermissions()=====" + accountInfo.getcPermissions());
            List<Permission> permissions = accountInfo.getcPermissions();
            for (Permission permission : permissions) {
                functionPermissionTokens.add(permission.getcPermissionType());
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("permissionName", permission.getcPermissionName());
                jsonObject.put("permissionToken", permission.getcPermissionType());
                functionPermissions.add(jsonObject);
            }
            session.setFunctionPermissionTokens(functionPermissionTokens);
            session.setFunctionPermission(functionPermissions);

            // 生成token，创建会话
            String sessionToken = BeanId.generateUUId();
            // sessionKey
            session.setToken(sessionToken);
            TokenSessionManager.getInstance().addDomainTokenSession(session);

//            httpSession.setAttribute(WebSecurityConfig.SESSION_KEY, sessionToken);

            JSONObject result = new JSONObject();
            result.put("Token", sessionToken);
            result.put("ExpiresIn", 0);

//            result.put("username", accountInfo.getcUsername());
//            result.put("permissionTokens", functionPermissionTokens);
//            result.put("permissionDetails", functionPermissions);
            return AjaxResponseData.reponseBody(ResultCode.SUCCESS, "success", result);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResponseData.reponseBody(ResultCode.SYSTEM_ERROR,"", null);
        }
    }

    @ApiOperation(value = "销毁token", notes = "请求参数:<br>" + "token 会话id")
    @ResponseBody
    @RequestMapping(value = "/DestroyAPIToken/{token}", method = RequestMethod.GET)
    public AjaxResponse DestroyAPIToken(@PathVariable String token) {
        try {
            // 退出登录，移除会话
            Integer userId = TokenUtil.getUserId(token);
            if (userId == null) {
                return AjaxResponse.reponseBody(ResultCode.SYSTEM_ERROR, "token not found");
            }

            Subject subject = SecurityUtils.getSubject();
            subject.logout();
            TokenSessionManager.getInstance().removeDomainTokenSession(token);
//            JSONObject result = new JSONObject();
//            result.put("userId", userId);
            return AjaxResponse.reponseBody(ResultCode.SUCCESS, "success");
        } catch (Throwable e) {
            LOGGER.error("", e);
            return AjaxResponse.reponseBody(ResultCode.SYSTEM_ERROR,"");
        }
    }
}
